<template>
  <div>
    <button @click="exportWord">exportWord</button>
    <button @click="getRomoteZipFile">解压</button>
  </div>
</template>

<script>
import docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
import JSZip from "jszip";
console.log(new JSZip());
class ExeJSZip {
  // 用于获取url地址对应的文件内容
  getBinaryContent(url, progressFn = () => {}) {
    return new Promise((resolve, reject) => {
      if (typeof url !== "string" || !/https?:/.test(url))
        reject(new Error("url 参数不合法"));
      JSZipUtils.getBinaryContent(url, {
        // JSZipUtils来自于jszip-utils这个库
        progress: progressFn,
        callback: (err, data) => {
          if (err) {
            reject(err);
          } else {
            resolve(data);
          }
        },
      });
    });
  }

  // 遍历Zip文件
  async iterateZipFile(data, iterationFn) {
    if (typeof iterationFn !== "function") {
      throw new Error("iterationFn 不是函数类型");
    }
    let zip;
    try {
      zip = await JSZip.loadAsync(data); // JSZip来自于jszip这个库
      zip.forEach(iterationFn);
      return zip;
    } catch (error) {
      throw new error();
    }
  }
}
export default {
  name: "App",
  data() {
    return {
      echartUrl1: "",
      clients: [
        {
          first_name: "John",
          last_name: "Doe",
          phone: "+44546546454",
        },
        {
          first_name: "Jane",
          last_name: "Doe",
          phone: "+445476454",
        },
      ],
    };
  },
  methods: {
    base64DataURLToArrayBuffer(dataURL) {
      const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
      if (!base64Regex.test(dataURL)) {
        return false;
      }
      const stringBase64 = dataURL.replace(base64Regex, "");
      let binaryString;
      if (typeof window !== "undefined") {
        binaryString = window.atob(stringBase64);
      } else {
        binaryString = new Buffer(stringBase64, "base64").toString("binary");
      }
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
      }
      return bytes.buffer;
    },
    exportWord() {
      var ImageModule = require("open-docxtemplater-image-module");
      // 点击导出word
      let _this = this;
      // 读取并获得模板文件的二进制内容
      JSZipUtils.getBinaryContent(
        "/static/model22.docx",
        function (error, content) {
          // exportTemplate.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
          // 抛出异常
          if (error) {
            throw error;
          }

          // 图片处理
          let opts = {};
          opts.centered = true; // 图片居中，在word模板中定义方式为{%%image}
          opts.fileType = "docx";
          opts.getImage = function (chartId) {
            return _this.base64DataURLToArrayBuffer(chartId);
          };
          opts.getSize = function () {
            return [600, 300];
          };

          let imageModule = new ImageModule(opts);
          // 创建一个PizZip实例，内容为模板的内容
          let zip = new PizZip(content);
          // 创建并加载docxtemplater实例对象
          let doc = new docxtemplater();
          doc.attachModule(imageModule);
          doc.loadZip(zip);

          // 设置模板变量的值
          doc.setData({
            first_name: "张三",
            last_name: "李四",
            clients: _this.clients,
          });

          try {
            // 用模板变量的值替换所有模板变量
            doc.render();
          } catch (error) {
            // 抛出异常
            let e = {
              message: error.message,
              name: error.name,
              stack: error.stack,
              properties: error.properties,
            };
            console.log(e);
            throw error;
          }
          // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
          let out = doc.getZip().generate({
            type: "blob",
            mimeType:
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          });
          // 将目标文件对象保存为目标类型的文件，并命名
          saveAs(out, "word文档名称.docx");
        }
      );
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
